/************************************************************************
                                                                     
   Xceed Ultimate ListBox for Silverlight                                                                                                                                            
   Copyright (C) 2010 Xceed Software Inc.    
                                                                     
   This program is provided to you under the terms of the GNU General Public  
   License version 2 as published by the Free Software Foundation. 
        
   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY, without even the implied warranty of 
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License along 
   with this program, if not, write to the Free Software Foundation, Inc., 
   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

   This program can be provided to you by Xceed Software Inc. under a
   proprietary commercial license agreement for use in non-Open Source
   projects. Visit Xceed.com to find the commercial edition of 
   Xceed Ultimate ListBox for Silverlight.                                    
                                                                      
 **********************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;

namespace Xceed.Silverlight.Data
{
  internal class SkipPagingEnumerator<T> : PagingEnumerator<T>
  {
    #region Static Fields

    private static readonly Guid JumpMoveAndFetchCallId = DataUtils.CreateCallId();

    #endregion Static Fields


    internal SkipPagingEnumerator(
      IAsyncEnumerator childEnumerator,
      Func<int> pageSize )
      : base( childEnumerator, pageSize )
    {
    }


    public override JumpMoveAndFetchAsyncResult BeginJumpMoveAndFetch(
      JumpMoveAndFetchParameters parameters,
      AsyncCallback callback,
      object state )
    {
      this.CheckMoveAndFetchParameters( parameters.ExpectedMoveCount, parameters.ExpectedFetchCount );

      bool isFirstPage = true;
      List<T> currentItems = new List<T>();
      EstimateInt64 totalItemsCount = null;
      Nullable<long> actualMoveCount = null;
      int remainingItemsCount = parameters.ExpectedFetchCount;

      // This anonymous method is fetching a new page.
      Func<AsyncCallback, object, IAsyncResult> getPage = null;
      getPage =
        ( AsyncCallback cb, object st ) =>
        {
          int nextFetchCount = this.GetFetchCount( remainingItemsCount );
          JumpMoveAndFetchParameters newParameters;

          // We must apply the expected move on the first page we fetch.
          if( isFirstPage )
          {
            isFirstPage = false;
            newParameters = parameters.CreateWithNewFetchCount( nextFetchCount );
          }
          // We use the last query result to get the next page.
          else
          {
            SourcePosition startingPosition = new ItemPosition( currentItems.Last() );

            newParameters = new JumpMoveAndFetchParameters(
                                  startingPosition,
                                  DataUtils.GetUnit( nextFetchCount ),
                                  nextFetchCount,
                                  parameters.ApproximateMove );
          }

          return base.BeginJumpMoveAndFetch( newParameters, cb, st );
        };

      // This anonymous method is handling a page and ask for a new page if necessary.
      Func<AsyncResult, IAsyncResult, DependentCallResult> getNextPage = null;
      getNextPage =
        ( AsyncResult par, IAsyncResult iar ) =>
        {
          JumpMoveAndFetchAsyncResult parentAsyncResult = ( JumpMoveAndFetchAsyncResult )par;
          JumpMoveAndFetchResult<T> pageResult = base.EndJumpMoveAndFetch( ( JumpMoveAndFetchAsyncResult )iar );

          if( m_disposed )
            return new DependentCallResult( null );

          // Set/Refresh the total items count.
          if( pageResult.TotalCount != null )
          {
            totalItemsCount = pageResult.TotalCount;
          }
          // The total items count we had previously is unreliable.
          else if( totalItemsCount != null )
          {
            totalItemsCount = totalItemsCount.ToEstimate();
          }

          if( !actualMoveCount.HasValue )
          {
            actualMoveCount = pageResult.ActualMoveCount;
          }

          // Append the fetched items to the final result.
          if( pageResult.FetchedItems != null )
          {
            ICollection<T> fetchedItems = pageResult.FetchedItems;

            currentItems.AddRange( fetchedItems );
            remainingItemsCount -= fetchedItems.Count * pageResult.GetFetchUnit();
          }

          // We do not have to fetch anymore page.
          if( ( !pageResult.Result ) || ( remainingItemsCount == 0 ) )
          {
            bool success = ( pageResult.Result ) && ( remainingItemsCount == 0 );
            ICollection<T> fetchedItems = ( success || currentItems.Count > 0 )
                                            ? currentItems
                                            : null;

            return new DependentCallResult(
                     new JumpMoveAndFetchResult<T>(
                       parentAsyncResult,
                       actualMoveCount,
                       fetchedItems,
                       success,
                       pageResult.EndPositionObject,
                       pageResult.EndPositionOffset,
                       totalItemsCount ) );
          }
          // Some items are still missing, we'll fetch another page.
          else
          {
            return new DependentCallResult( null, getPage, getNextPage );
          }
        };

      JumpMoveAndFetchAsyncResult asyncResult = new JumpMoveAndFetchAsyncResult(
                                                  SkipPagingEnumerator<T>.JumpMoveAndFetchCallId,
                                                  callback,
                                                  state,
                                                  parameters );

      asyncResult.Start( getPage, getNextPage );

      return asyncResult;
    }

    public override JumpMoveAndFetchResult<T> EndJumpMoveAndFetch(
      JumpMoveAndFetchAsyncResult asyncResult )
    {
      asyncResult.ValidateCallEnd( SkipPagingEnumerator<T>.JumpMoveAndFetchCallId );

      return asyncResult.GetCallResult<JumpMoveAndFetchResult<T>>();
    }

    protected override void Dispose( bool disposing )
    {
      m_disposed = true;

      base.Dispose( disposing );
    }


    #region Private Fields

    private bool m_disposed; //false

    #endregion
  }
}
